﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace AutoUpdater
{
    [PersistJobDataAfterExecution]
    class GitJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() =>
            {

                using (var resetExecutor = new ProcessExecutor(Config.workingDirectory, "git", "-- *"))
                {
                    resetExecutor.OnOutputDataReceived += (sender, str) =>
                    {
                        if (str is null)
                            return;

                        Console.WriteLine(str);
                    };
                    resetExecutor.Execute();
                }
                
                var executor = new ProcessExecutor(Config.workingDirectory, "git", "pull");

                StringBuilder sb = new StringBuilder();

                executor.OnOutputDataReceived += (sender, str) =>
                {
                    if (str is null)
                        return;

                    sb.AppendLine(str);
                };
                executor.OnErrorDataReceived += (sender, str) =>
                {
                    if (str is null)
                        return;

                    Console.WriteLine(str);
                };

                executor.Execute();
                executor.Dispose();

                string output = sb.ToString();
                if (output.StartsWith("Already up to date."))
                    return;

                if (string.IsNullOrWhiteSpace(output))
                    return;

                if (!output.StartsWith("Updating"))
                    return;

                Log4NetHelper.LogInput("git", sb.ToString());

                var scriptDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
                if (Directory.Exists(scriptDirectory)) {
                    var files = Directory.GetFiles(scriptDirectory, "*.bat");
                    foreach (var file in files) {

                        Console.WriteLine(file);
                        FileInfo fileInfo = new FileInfo(file);
                        
                        using (var doExecutor = new ProcessExecutor("", file))
                        {
                            doExecutor.OnOutputDataReceived += (sender, str) =>
                            {
                                if (str is null)
                                    return;

                                Console.WriteLine(str);
                            };
                            doExecutor.Execute();
                        }
                    }
                }

            });
        }
    }
}
